package com.ruoyi.ai.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.uuid.UUID;
import com.ruoyi.ai.domain.vo.WechatLoginVO;
import com.ruoyi.ai.mapper.AiUserMapper;
import com.ruoyi.ai.domain.AiUser;
import com.ruoyi.ai.service.WechatLoginService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信登录服务实现
 */
@Service
public class WechatLoginServiceImpl implements WechatLoginService {

    private static final Logger log = LoggerFactory.getLogger(WechatLoginServiceImpl.class);

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private AiUserMapper userMapper;

    @Value("${wechat.appid}")
    private String appid;

    @Value("${wechat.secret}")
    private String secret;

    @Override
    public Map<String, Object> wechatLogin(WechatLoginVO loginVO) {
        // 1. 通过code获取微信openid和session_key
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid +
                "&secret=" + secret + "&js_code=" + loginVO.getCode() + "&grant_type=authorization_code";

        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
        JSONObject jsonObject = JSON.parseObject(response.getBody());
        
        log.info("微信登录返回: {}", jsonObject);

        // 检查返回结果
        if (jsonObject.containsKey("errcode") && jsonObject.getIntValue("errcode") != 0) {
            throw new RuntimeException("获取微信openid失败: " + jsonObject.getString("errmsg"));
        }

        String openid = jsonObject.getString("openid");
        String sessionKey = jsonObject.getString("session_key");

        if (StringUtils.isEmpty(openid)) {
            throw new RuntimeException("获取微信openid失败");
        }

        // 2. 根据openid查询用户是否存在
        AiUser user = userMapper.selectUserByOpenid(openid);
        
        // 3. 用户不存在则注册新用户
        if (user == null) {
            user = new AiUser();
            user.setUserName("wx_" + UUID.randomUUID().toString().substring(0, 8));
            user.setNickName(loginVO.getNickName());
            user.setAvatar(loginVO.getAvatar());
            user.setSex(loginVO.getSex());
            user.setOpenid(openid);
            user.setUserType(loginVO.getUserType());
            user.setStatus(loginVO.getStatus());
            user.setDelFlag(loginVO.getDelFlag());
            
            // 保存用户
            userMapper.insertUser(user);
        } else {
            // 更新用户信息
            user.setNickName(loginVO.getNickName());
            user.setAvatar(loginVO.getAvatar());
            user.setSex(loginVO.getSex());
            
            userMapper.updateUser(user);
        }

        // 4. 生成token
        String token = UUID.randomUUID().toString();
        
        // 5. 返回结果
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> userInfo = new HashMap<>();
        
        userInfo.put("userId", user.getUserId());
        userInfo.put("userName", user.getUserName());
        userInfo.put("nickName", user.getNickName());
        userInfo.put("avatar", user.getAvatar());
        userInfo.put("sex", user.getSex());
        
        result.put("token", token);
        result.put("userInfo", userInfo);
        
        return result;
    }
}